﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs; 

namespace WPF.Core
{ 
    public class DialogViewModel : BindableBase, IDialogAware
    {
        public DialogViewModel()
        {
            SaveCommand = new DelegateCommand(Save);
            CancelCommand = new DelegateCommand(Cancel);
        }

        private bool isBusy;

        public bool IsBusy
        {
            get { return isBusy; }
            set { isBusy = value; RaisePropertyChanged(); }
        }

        public DelegateCommand SaveCommand { get; private set; }
        public DelegateCommand CancelCommand { get; private set; }

        public string Title { get; set; } 

        public event Action<IDialogResult> RequestClose;

        public virtual bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        }

        private void Cancel()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));
        }

        public virtual void Save()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
        }

        public virtual void OnDialogOpened(IDialogParameters parameters)
        {
        }

        /// <summary>
        /// 执行等待任务
        /// </summary>
        /// <param name="func"></param>
        public async Task SetBusyAsync(Func<Task> func)
        {
            if (IsBusy) return;

            try
            {
                IsBusy = true;
                await func();
            }
            finally
            {
                IsBusy = false;
            }
        }
    }
}
